package com.tiancheng.trade.settlement.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * json util
 *
 * @author kellen
 * @date 2019/12/30
 */
@Component
public class JacksonJsonUtil {

    @Autowired
    private ObjectMapper objectMapper;

    /**
     * 序列化对象
     *
     * @param obj
     * @return
     */
    public String toJson(Object obj) {
        try {
            return objectMapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 反序列化json
     *
     * @param jsonStr
     * @param clazz
     * @param <T>
     * @return
     */
    public <T> T fromJson(String jsonStr, Class<T> clazz) {
        try {
            return objectMapper.readValue(jsonStr, clazz);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }

}
